package com.yf.screenshot

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.alibaba.fastjson.JSON
import com.wink_172.library.activity.DownAppActivity
import com.wink_172.library.activity.SmartActivity
import com.wink_172.library.model.Constants
import com.wink_172.library.utils.CommonUtils.downLoadFile
import com.yangfan.screenshot.ScreenShotManager
import com.yangfan.screenshot.ScreenShotManager.ScreenShotStateCallback
import com.yangfan.screenshot.log.LogUtil
import com.yangfan.screenshot.utils.DeviceUtils
import com.yangfan.screenshot.utils.PermissionUtil
import com.yangfan.screenshot.viewmodel.AppViewModel
import org.xutils.x
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader


class MainActivity : SmartActivity() {


    open fun readTxt(path: String): String {
        var str = ""
        try {
            val urlFile = File(path)
            val isr = InputStreamReader(FileInputStream(urlFile), "UTF-8")
            val br = BufferedReader(isr)
            var mimeTypeLine: String? = null
            while (br.readLine().also { mimeTypeLine = it } != null) {
                str = str + mimeTypeLine
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return str
    }

    private val TAG = MainActivity::class.java.simpleName
    private var appViewModel: AppViewModel? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        appViewModel = ViewModelProvider((applicationContext as App)).get(
            AppViewModel::class.java
        )
        val textView = findViewById<TextView>(R.id.version)
        val update_app = findViewById<TextView>(R.id.update_app)
        textView.text = "版本：" + BuildConfig.VERSION_NAME
        findViewById<TextView>(R.id.confirm).setOnClickListener {
   onBackPressed()

        }

//      shareLink(null)
        checkVersion()
        update_app.setOnClickListener {
            checkVersion()
        }
        ScreenShotManager.getInstance()
            .setScreenShotStateCallback(object : ScreenShotStateCallback {
                override fun onShotCompleted(bitmap: Bitmap) {
                    LogUtil.d(TAG, "onShotComplete bitmap ==== "+bitmap.height)
                    appViewModel!!.bitmapLiveData.postValue(bitmap)
                    val intent = Intent(this@MainActivity, PreviewActivity::class.java)
                    this@MainActivity.startActivity(intent)
                }

                override fun onStitchProgress(index: Int, total: Int) {
                    LogUtil.d(TAG, "onShotBitmapList index ===== $index;total = $total")
                    val intent = Intent(this@MainActivity, PreviewActivity::class.java)
                    intent.putExtra("progress", index)
                    intent.putExtra("total", total)
                    this@MainActivity.startActivity(intent)
                }

                override fun onError() {}
            })
    }
    override fun onBackPressed() {
       super.onBackPressed()
    }

    fun checkVersion() {
        val update_app = findViewById<TextView>(R.id.update_app)
        val version_web =
            "https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com/version/screen_app_version.txt"
        val version_path = getCachePath(x.app()) + "/version.txt"
        downLoadFile(
            version_web, version_path,
            object :
                com.wink_172.library.callback.ICallback {
                override fun onSendEvent(
                    event: Int,
                    vararg args: Any?
                ) {//这个callback用的非常巧妙    //这里因为不能传递非Serialiazable,对象 所以需要精简代码

                    if (event == Constants.EventEnum.网络请求成功.ordinal) {
                        val text = readTxt(args[0] as String)
                        Log.e(TAG, "onSendEvent: ====>>" + text)
                        val version = JSON.parseObject(
                            text,
                            AppVersion::class.java
                        )
                        val check = TextUtils.equals(
                            BuildConfig.VERSION_NAME,
                            version.version_name
                        )
                        Log.e(
                            TAG,
                            "check: ====>>" + BuildConfig.VERSION_NAME + "  " + version.version_name + "   " + check
                        )
                        if (check == false
                        ) {
                            update_app.setText("有新版本需要更新")
                            DialogUtils.showSingleBtnDialog(activity,
                                "更新提示",
                                "有新版本更新",
                                "立即更新",
                                false,
                                object :
                                    com.wink_172.library.callback.ICallback {
                                    override fun onSendEvent(
                                        event: Int,
                                        vararg args: Any?
                                    ) {//这个callback用的非常巧妙    //这里因为不能传递非Serialiazable,对象 所以需要精简代码

                                        val tt = "screen_shot_" + version.version_name + ".apk"
                                        val web_url =
                                            version.web_url + tt
                                        val down_load_path =
                                            getCachePath(x.app()) + tt

                                        DownAppActivity.startActivity(
                                            activity,
                                            web_url,
                                            down_load_path
                                        )

                                    }
                                }
                            )


//    screen_shot_v1.0.0.apk
                        } else {
                            update_app.setText("当前已经是最新版本")
                        }
                    }
                }
            }
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        ScreenShotManager.getInstance().unBindService()
    }

    fun getCachePath(context: Context): String {
        var cachePath = ""
        cachePath =
            if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() || !Environment.isExternalStorageRemovable()) {
                //外部存储可用
                context.externalCacheDir!!.path
            } else {
                //外部存储不可用
                context.cacheDir.path
            }
        return cachePath
    }

    override fun onResume() {
        super.onResume()

        val permiss= if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Manifest.permission.READ_MEDIA_IMAGES
        }else{
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        }


        if (checkSelfPermission(permiss) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(permiss), 201)
            return
        }
        if (!DeviceUtils.isBackgroundStartAllowed(this)) {
            Toast.makeText(applicationContext, "需要开启后台弹出界面权限", Toast.LENGTH_SHORT)
                .show()
            return
        }
        if (!PermissionUtil.hasAccessibilityPermission(this)) {
            LogUtil.d(TAG, "跳转到无障碍设置界面")
            PermissionUtil.jumpAccessibilitySetting(this)
        }
    }
}